/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.ForumpostList;
import com.tzinfo.tzb.domain.ForumpostList.ForumpostData;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzb.view.adapter.TzbImageAdapter;
import com.tzinfo.tzb.view.adapter.TzbImageClickAdapter;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.util.ResFinder;

public class TzbBangForumpostListActivity extends TzbBaseActivity implements
        IXListViewListener, AdapterView.OnItemClickListener {
    // 标志
    private boolean isCollected = false;
    private boolean isNotification = false;

    // 参数
    private String FID = null, TID = null, Subject = null;
    private int collectType = 1;

    // 适配器
    private TzbImageClickAdapter imageAdapter;

    // 数据
    private List<Map<String, Object>> data;
    private ForumpostList forumpostList;

    // UI组件
    private YXWXListView listView;
    private TextView text_theme_title;
    private Button bt_collection;

    // 其他
    private Handler mHandler;
    private int page = 1; // 页码
    private int pagesize = 10; // 每页条数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tzb_ac_main_bang_forumpostlist);
        initParameter();
        initUI();
        initData();
    }

    private void initParameter() {
        Intent thisIntent = this.getIntent();
        FID = thisIntent.getStringExtra("FID");
        TID = thisIntent.getStringExtra("TID");
        isNotification = thisIntent.getBooleanExtra("isNotification", false);
        isCollected = thisIntent.getBooleanExtra("isCollected", false);
        Subject = thisIntent.getStringExtra("Subject");
        if (!isNotification) {
            if (TID == null || "".equals(TID) || FID == null || "".equals(FID)) {
                TID = TzbCommonData.forumthreadData.getTid() + "";
                FID = TzbCommonData.classSubMenu.getForumId() + "";
                Subject = TzbCommonData.forumthreadData.getSubject();
            }
        }
        mHandler = new Handler();
    }

    private void initUI() {
        // 加载滚动进入条
        mProgressBar = (ProgressBar) this.findViewById(ResFinder.getR(this,
                "R.id.progressbar_loding"));
        text_theme_title = (TextView) ResFinder.findViewById(this,
                "R.id.text_theme_title");
        bt_collection = (Button) ResFinder.findViewById(this,
                "R.id.bt_collection");
        if (isCollected) {
            bt_collection.setText("取消收藏");
            collectType = 2;
        }

        text_theme_title.setText(Subject);
        listView = (YXWXListView) ResFinder
                .findViewById(this, "R.id.xListView");
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setOnItemClickListener(this);
    }

    private void initData() {
        if (forumpostList == null) {
            requestInfo();
        } else {
            initListView();
        }
    }

    // 重载，默认请求新数据
    private void requestInfo() {
        page = 1;
        requestInfo(TzbCommonData.NOPULL_LOAD);
    }

    private void requestInfo(int type) {
        final int type2 = type;
        if (type == TzbCommonData.NOPULL_LOAD) {
            showProgressBar();
        }
        String url = "";
        if (isNotification) {
            url = ResFinder.getResString(this,
                    "R.string.tzb_url_ForumpostList")
                    + "?tid=" + TID + "&Page=" + page + "&Pagesize=" + pagesize;
        } else {
            url = ResFinder.getResString(this,
                    "R.string.tzb_url_ForumpostList")
                    + "?tid="
                    + TID
                    + "&fid="
                    + FID
                    + "&Page="
                    + page
                    + "&Pagesize=" + pagesize;
        }

        OutLog.LogE("url", url);
        GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
        galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<ForumpostList>() {
                }.getType();

                ForumpostList temp = gson.fromJson(arg0, type);
                if (temp.isSuccess()) {
                    if (type2 == TzbCommonData.PULL_LOAD_MORE) {
                        int size = temp.getData().size();
                        for (int i = 0; i < size; i++) {
                            forumpostList.getData().add(temp.getData().get(i));
                        }
                        if (size < 10) {
                            listView.setPullLoadEnable(false);
                            Toast.makeText(TzbBangForumpostListActivity.this,
                                    "已经是最后一页！", Toast.LENGTH_LONG).show();
                        }
                    } else if (type2 == TzbCommonData.PULL_REFLASH
                            || type2 == TzbCommonData.NOPULL_LOAD) {
                        forumpostList = temp;
                        if (temp.getData().size() < 10) {
                            listView.setPullLoadEnable(false);
                        } else {
                            listView.setPullLoadEnable(true);
                        }
                    }
                    initListView();
                    onLoadFinish();
                } else {
                    Toast.makeText(TzbBangForumpostListActivity.this,
                            "数据加载失败…", Toast.LENGTH_LONG).show();
                }
                removeProgressBar();
            }
        });
    }

    private void initListView() {
        // 初始化data
        if (data == null) {
            data = new ArrayList<Map<String, Object>>();
        } else {
            data.clear();
        }
        List<ForumpostData> list = forumpostList.getData();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            String image = list.get(i).getUserinfo().getAvatar();
            map.put("uid", list.get(i).getUserinfo().getUsername());
            map.put("Avatar", image);
            String img_attachment;
            if (list.get(i).getAttachment() != null
                    && list.get(i).getAttachment().size() != 0) {
                img_attachment = list.get(i).getAttachment().get(0)
                        .getAttachment();
                map.put("img_attachment", img_attachment);
            }

            map.put("Subject", list.get(i).getSubject());
            String message = list.get(i).getMessage();
            map.put("Message",
                    message == null
                            || "null".equals(message.toLowerCase().trim()) ? ""
                            : message);
            String netname = list.get(i).getUserinfo().getNetname();
            if (netname == null || "".equals(netname.trim())) {
                netname = list.get(i).getUserinfo().getUsername();
            }
            map.put("Netname", netname);
            String Regdate = YXWDateUtil.getTimeInterval(list.get(i)
                    .getDateline(), "MM/dd/yyyy HH:mm:ss");
            map.put("Regdate", Regdate);
            // 设置几秒前、几分前、几小时前等
            String sDateline = YXWDateUtil.getTimeInterval(list.get(i)
                    .getDateline(), "MM/dd/yyyy HH:mm:ss");
            map.put("Dateline", sDateline);
            map.put("Credits", "积分：" + list.get(i).getUserinfo().getCredits());
            data.add(map);
        }
        if (imageAdapter == null) {
            imageAdapter = new TzbImageClickAdapter(
                    TzbBangForumpostListActivity.this, data, R.layout.tzb_item_forumpost,
                    new String[]{"uid", "Avatar", "Subject", "Message",
                            "Netname", "Regdate", "Dateline", "Credits",
                            "img_attachment"}, new int[]{R.id.list_id,
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_image"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_title"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_context"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_netname"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_regdate"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_time"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.list_item_credits"),
                    ResFinder.getR(TzbBangForumpostListActivity.this,
                            "R.id.img_attachment")}

            );
            listView.setAdapter(imageAdapter);
        } else {
            imageAdapter.notifyDataSetChanged();
        }
    }

    // // onclick方法
    // @Override
    // public void goTabHostBack(View v) {
    // this.finish();
    // // Intent intent = new Intent(this,
    // // TzbMyBangForumthreadListAcivity.class);
    // // LoadActivityWithTabhost(intent, TzbTabMyBangGroup.activityGroup);
    // }

    // onclick
    public void huitie(View v) {
        if (TztData.userInfo != null) {
            Intent intent = new Intent(this, TzbBangFatieActivity.class);
            intent.putExtra("fid", Integer.parseInt(FID));
            intent.putExtra("tid", Integer.parseInt(TID));
            intent.putExtra("stitle", Subject);
            startActivityForResult(intent, 1);
        } else {
            Toast.makeText(this, "亲，该功能需要登录才能使用", Toast.LENGTH_SHORT).show();
        }

    }

    // onclick
    public void onShoucang(View v) {
        if (TztData.userInfo != null) {
            dialog.show();
            String url = "";
            url = ResFinder.getResString(this, "R.string.tzb_url_ForumCollect")
                    + "?sessionid=" + TztData.userInfo.getData().getSessionID()
                    + "&tid=" + TID + "&type=" + collectType;

            OutLog.LogE("yxw", url);
            GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
            galHttpRequest
                    .startAsynRequestString(new GalHttpLoadTextCallBack() {

                        @Override
                        public void textLoaded(String arg0) {
                            OutLog.LogE("yxw", "json:" + arg0);
                            Gson gson = new Gson();
                            java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                            }.getType();
                            DefaultResult result = gson.fromJson(arg0, type);
                            if (result.isSuccess()) {
                                if (isCollected) {
                                    isCollected = false;
                                    collectType = 1;
                                    bt_collection.setText("收藏");
                                    Toast.makeText(
                                            TzbBangForumpostListActivity.this,
                                            "已取消收藏", Toast.LENGTH_SHORT).show();

                                } else {
                                    isCollected = true;
                                    collectType = 2;
                                    bt_collection.setText("取消收藏");
                                    Toast.makeText(
                                            TzbBangForumpostListActivity.this,
                                            "收藏成功", Toast.LENGTH_SHORT).show();
                                }
                                TzbTabMyActivity.reflashInfo = true;
                                // TzbBangForumpostListActivity.this.finish();
                            } else {
                                Toast.makeText(
                                        TzbBangForumpostListActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }
                    });
        } else {
            Toast.makeText(this, "亲，该功能需要登录才能使用", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void goback(View view) {
        Intent intent = new Intent();
        intent.putExtra(TzbCommonData.IS_NEED_REFLASH, true);
        TzbTabMyActivity.isNeedReLoadNum = true;
        setResult(1, intent);
        this.finish();
    }

    private void onLoadFinish() {
        listView.stopRefresh();
        listView.stopLoadMore();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        listView.setRefreshTime(df.format(new Date()));
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                requestInfo(TzbCommonData.PULL_REFLASH);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                requestInfo(TzbCommonData.PULL_LOAD_MORE);
            }
        }, 2000);
    }

    // onclick
    public void goGerenPage(View v) {
        TextView textView = (TextView) ResFinder
                .findViewById(v, "R.id.list_id");
        String username = textView.getText().toString();
        // int posi = Integer.parseInt(uidTextView.getText().toString());
        Intent intent = new Intent(this, TzbUserInfoActivity.class);
        intent.putExtra("username", username);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 1) {
                boolean isOk = data.getBooleanExtra(TzbCommonData.IS_OK, false);
                if (isOk) {
                    requestInfo();
                }
            }
        }
        if (requestCode == 2)requestInfo();
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(TztData.isUserLogin){
            //重写HuiTieActivity，之后修改
            List<ForumpostData> list = forumpostList.getData();

            startActivityForResult(new Intent(this, HuiTieActivity.class).putExtra("fid", list.get(position - 1).getFid())
                    .putExtra("tid", list.get(position - 1).getTid())
                    .putExtra("ouid",list.get(position-1).getUserinfo().getUid())
                    .putExtra("tag", "[quote][size=2][color=#999999]" + list.get(position - 1).getUserinfo().getUsername() + "发表于" + list.get(position - 1).getDateline()+"[/color][/size]"
                            +list.get(position - 1).getMessage()+"[/quote]"),2);

        }
        else {
            Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
        }


    }
}
